<template>
  <div class="Uploads">
    <ul slot="default"
        class="el-upload-list el-upload-list--picture-card">
      <li v-for="(item, index) in fileList"
          :key="index"
          :tabindex="index"
          class="el-upload-list__item is-ready">
        <div>
          <img v-if="item.fileType.split('/')[0] === 'image'"
               :src="item.url"
               alt
               class="el-upload-list__item-thumbnail" />
          <video v-else
                 :src="item.url"
                 class="avatar-video"
                 autoplay>您的浏览器不支持视频播放</video>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview">
              <i class="el-icon-zoom-in"
                 @click="previewFile(item, index)"></i>
            </span>
            <span class="el-upload-list__item-delete">
              <i class="el-icon-download"
                 @click="downloadFile(item, index)"></i>
            </span>
            <span class="el-upload-list__item-delete">
              <i class="el-icon-delete"
                 @click="deleteFile(item, index)"></i>
            </span>
          </span>
        </div>
      </li>
      <li :tabindex="1000000"
          style="border:none"
          class="el-upload-list__item is-ready">
        <el-upload :class="{ disabled: uploadDisabled }"
                   :action="httpURL"
                   :headers="{ Authorization: token }"
                   :show-file-list="false"
                   :file-list="fileList"
                   :limit="limit"
                   list-type="picture-card"
                   :before-upload="beforeImgUpload"
                   :on-success="handleImgSuccess"
                   :on-error="handleImgError"
                   :on-exceed="handleExceed"
                   :accept="accept"
                   :on-progress="uploadVideoProcess">
          <i v-if="!percentage"
             slot="default"
             class="el-icon-plus"></i>
        </el-upload>
        <el-progress v-if="percentage"
                     type="circle"
                     :percentage="percentage"></el-progress>
        <el-dialog :visible.sync="dialogVisible"
                   append-to-body
                   :close-on-click-modal="false">
          <video v-if="dialogType === 'video'"
                 :src="dialogImageUrl"
                 width="100%"
                 autoplay
                 controls="controls">
            您的浏览器不支持视频播放
          </video>
          <img v-else
               width="100%"
               :src="dialogImageUrl"
               alt />
        </el-dialog>
      </li>
    </ul>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'Uploads',
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    action: {
      type: String,
      default: 'files/upload'
    },
    accept: {
      type: String,
      default: 'image/*'
    },
    typeText: {
      type: String,
      default: '支持格式：*.png,*.jpg,*.jpge 支持最大2M'
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      httpURL: process.env.VUE_APP_BASE_API + 'system/files/upload',
      fileList: [],
      percentage: '',
      imageUrl: '',
      fileType: 'image/*',
      uid: null,
      token: 'bearer ' + getToken(),
      dialogImageUrl: '',
      dialogVisible: false,
      dialogType: '',
      disabled: false
    }
  },
  computed: {
    uploadDisabled: function () {
      return this.fileList.length >= this.limit
    }
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.error('最大限制上传' + this.limit + '个文件，请先删除已上传文件')
    },
    beforeImgUpload(file) {
      if (file.type.split('/')[0] !== 'image' && file.type.split('/')[0] !== 'video') {
        this.$message.error(`上传文件类型错误`)
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 128
      if (!isLt2M) {
        this.$message.error(`上传图片/视频大小不能超过128MB!`)
      }
      return isLt2M
    },
    handleImgSuccess(response, file, fileList) {
      console.log(response)
      response.fileType = file.raw.type
      if (this.multiple) {
        this.fileList.push(response)
        this.$emit('handleImgSuccess', this.fileList)
      } else {
        this.fileList = [response]
        this.$emit('handleImgSuccess', this.fileList.length ? this.fileList[0] : false)
      }
      this.$message.success(`${response.fileType.split('/')[0] === 'image' ? '图片' : '视频'}上传成功`)
      this.$emit('success', response)
    },
    handleImgError() {
      this.$message.error(`文件上传失败`)
    },
    uploadVideoProcess(event, file, fileList) {
      this.percentage = parseInt(event.percent)
      if (event.percent === 100) {
        this.percentage = ''
      }
    },
    previewFile(item, index) {
      console.log(item)
      this.dialogType = item.fileType.split('/')[0]
      this.dialogVisible = true
      this.dialogImageUrl = item.url
    },
    downloadFile(item, index) {
      const eleLink = document.createElement('a')
      eleLink.download = item.name
      eleLink.href = item.url
      eleLink.click()
      eleLink.remove()
    },
    deleteFile(item, index) {
      this.fileList.splice(index, 1)
      this.$emit('success', this.fileList)
    }
  }
}
</script>

<style lang="scss" scoped>
.Uploads {
  display: flex;
  flex-wrap: wrap;
  .avatar-video {
    width: 148px;
    height: 148px;
  }
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  .disabled .el-upload--picture-card {
    display: none;
  }
}
</style>
